# -*- coding = utf-8 -*-
# @Time : 2024/6/9 17:50
# @Author : 0505200213石浪
# @File : comments.py
# @Software : PyCharm


from flask import request, jsonify, session, redirect, url_for

import utils
from . import bp
from db_operations import Database
import os

db = Database()
dynamic = 'static/assets/img/dynamic'
os.makedirs(dynamic, exist_ok=True)


# 识别是否有二次评论
@bp.route('/get_is_second_comments', methods=['GET'])
def get_is_second_comments():
    sql = "SELECT user_comment_id FROM movieFriends.second_comments;"
    second_comments = db.execute(sql, )
    return jsonify(second_comments)


# 获取二次评论数据
@bp.route('/get_second_comments', methods=['GET'])
def get_second_comments():
    comment_id = request.args.get('commentId')  # 获取前端传递的 commentId 参数
    second_comments = utils.get_second_comments_from_database(comment_id)
    # 将二次评论数据以 JSON 格式返回给前端
    return jsonify(second_comments)


# 提交评论的功能
@bp.route('/submit_comment/<username>', methods=['POST'])
def submit_comment(username):
    if request.method == 'POST':
        movie_id = request.form['movieId']
        content = request.form['comment']
        sql = "INSERT INTO movieFriends.comments (movie_id, content, username, avatar) VALUES (%s, %s, %s, %s)"
        db.execute(sql, (movie_id, content, username, session[username]['avatar']))
        return redirect(url_for('main.movie_detail', username=username, movieId=movie_id))


# 评论回复
@bp.route('/submit_reply/<username>', methods=['POST'])
def submit_reply(username):
    data = request.json
    user_comment_id = data['user_comment_id']
    content = data['content']
    sql = "INSERT INTO movieFriends.second_comments (user_comment_id, user_id, content, user_name, avatar) VALUES (" \
          "%s, %s, %s, %s, %s) "
    params = (user_comment_id, session[username]['id'], content, username, session[username]['avatar'])
    db.execute(sql, params)
    return jsonify({"message": "回复成功"}), 200
